using B.S.Data.MES.API.Applications.BaseData.Command.MaterialGroupCommand;
using B.S.Domain.BasicData.MaterialManagement.MaterialGroups;
using B.S.Domain.BasicData.MaterialManagement.Material_type;
using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using B.S.Domain.Dto.WuLiaoDto;

namespace B.S.Data.MES.API.Applications.BaseData.CommandHandlers.MaterialGroupCommandHandlers
{
    public class GetMaterialGroupsWithTypeCommandHandler : IRequestHandler<GetMaterialGroupsWithTypeCommand, APIRequst<List<GropDto>>>
    {
        private readonly IBaseRepository<Material_group> _materialGroupRepository;
        private readonly IBaseRepository<Material_type> _materialTypeRepository;

        public GetMaterialGroupsWithTypeCommandHandler(
            IBaseRepository<Material_group> materialGroupRepository,
            IBaseRepository<Material_type> materialTypeRepository)
        {
            _materialGroupRepository = materialGroupRepository;
            _materialTypeRepository = materialTypeRepository;
        }

        public Task<APIRequst<List<GropDto>>> Handle(GetMaterialGroupsWithTypeCommand request, CancellationToken cancellationToken)
        {
            // 使用LINQ实现物料群组表与物料类型表的内连接查询
            var query = from mg in _materialGroupRepository.GetAll()
                        join mt in _materialTypeRepository.GetAll() on mg.Materialtypeid equals mt.Materialtypeid
                        where mt.Materialtypeid == request.Materialtypeid
                        select new GropDto
                        {
                            MaterId = mg.MaterId,
                            Materialcode = mg.Materialcode,
                            Materialname = mg.Materialname,
                            Materialtypeid = mg.Materialtypeid,
                            Id = mg.Id,
                            Materialdescription = mg.Materialdescription,
                            MaterialtypeName = mt.MaterialtypeName,
                            CreateName=mg.CreateName,
                            CreateTime=mg.CreateTime,
                            UpdateTime=mg.UpdateTime
                        };

            // 按物料编码排序
            var result = query.OrderBy(x => x.Materialcode).ToList();

            return Task.FromResult(new APIRequst<List<GropDto>>
            {
                Code = RequstCode.成功,
                Msg = RequstCode.成功.ToString(),
                Data = result
            });
        }
    }
}